package ac.il.technion.cs236369.hw5.core.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ac.il.technion.cs236369.hw5.core.entities.Role;
import ac.il.technion.cs236369.hw5.core.entities.User;

import com.google.gson.Gson;

/**
 * Servlet implementation class ListAvailableRoles
 */
public class ListAvailableRoles extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final EntityManagerFactory emf = Persistence.createEntityManagerFactory( "jpaProvider");
    
	public static class Envelope {
		private List<Role> items;

		public Envelope( List<Role> roles) {
			items = new ArrayList<Role>( );
			for ( Role $ : roles) {
				Role role = new Role( );
				role.setLevel($.getLevel( ));
				role.setRole($.getRole( ));
//				for ( User u : $.getUsers( )) {
//					User _user = new User( );
//					_user.setActivityStatus(u.getActivityStatus( ));
//					_user.setFirstName(u.getFirstName());
//					_user.setLastName(u.getLastName( ));
//					_user.setLoginName(u.getLoginName());
//					_user.setPhoneNumber(u.getPhoneNumber( ));
//					role.getUsers().add(_user);
//				}
				items.add(role);
			}
		}
		public List<Role> getItems() {
			return items;
		}

		public void setItems(List<Role> roles) {
			this.items = roles;
		}
	}
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListAvailableRoles() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = emf.createEntityManager( );
		try {
			User user = em.find( User.class, request.getUserPrincipal( ));
			List<Role> roles = em.createQuery( "SELECT r FROM Role r").getResultList( );
			List<Role> result = new ArrayList<Role>( );
			for ( Role role : roles) {
				if ( role.getLevel( ) >= user.getPermission( ).getLevel( )) {
					result.add( role);
				}
			}
			Envelope envelope = new Envelope( result);
			Gson gson = new Gson( );
			response.getWriter( ).println( gson.toJson(envelope));
		} catch( Exception e) {
			e.printStackTrace( );
		} finally {
			em.close( );
		}
	}
}